package com.gitee.center.runtime;

import com.gitee.center.runtime.annotation.*;
import com.gitee.center.runtime.def.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

@Component
public class RegistryFactory implements InitializingBean {

    static List<RegistryEntry> validRegistryEntries = new ArrayList<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO 自动注册
        validRegistryEntries.add(new RegistryEntry(Domain.class, () -> new DomainDef()));
//        validRegistryEntries.add(new RegistryEntry(DomainService.class, () -> new DomainServiceDef()));
//        validRegistryEntries.add(new RegistryEntry(Specification.class, () -> new SpecificationDef()));
        validRegistryEntries.add(new RegistryEntry(Step.class, () -> new StepDef()));
        validRegistryEntries.add(new RegistryEntry(DomainAbility.class, () -> new DomainAbilityDef()));
        validRegistryEntries.add(new RegistryEntry(Policy.class, () -> new PolicyDef()));
        validRegistryEntries.add(new RegistryEntry(Partner.class, () -> new PartnerDef()));
//        validRegistryEntries.add(new RegistryEntry(Pattern.class, () -> new PatternDef()));
        validRegistryEntries.add(new RegistryEntry(Extension.class, () -> new ExtensionDef()));
    }

    void register(ApplicationContext applicationContext) {
        for (RegistryEntry registryEntry : validRegistryEntries) {
            for (Object springBean : applicationContext.getBeansWithAnnotation(registryEntry.annotation).values()) {
                registryEntry.create().registerBean(springBean);
            }
        }
    }

    private static class RegistryEntry {
        private final Class<? extends Annotation> annotation;
        private final Supplier<IRegistryAware> supplier;
        RegistryEntry(Class<? extends Annotation> annotation, Supplier<IRegistryAware> supplier) {
            this.annotation = annotation;
            this.supplier = supplier;
        }

        IRegistryAware create() {
            return supplier.get();
        }
    }
}
